import { appProductListServer } from '@/services/productList';
import { splitPrice, transform2px, transformConfig } from '@/utils/customModule';
import utils from '@/utils/index';
import { Image, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import Icon from '../../Icon';
import { defaultVisibleEnums } from '../../moduleConstants';
import {
  recommendGoodsCartStyle,
  recommendGoodsGoodsAlign,
  recommendGoodsStyle,
} from '../constants';
import './index.scss';

const GoodsStyleName = {
  [recommendGoodsStyle.line]: 'flatten',
  [recommendGoodsStyle.card]: 'cards',
  [recommendGoodsStyle.border]: 'border',
};

const styleConfig = {
  item: ['borderRadius'],
  background: (styleSettingRender) => {
    //  扁平 不用管
    if (styleSettingRender.goodsStyle === recommendGoodsStyle.line) {
      return {
        backgroundColor: '#fff',
      };
    }

    return {
      backgroundColor: styleSettingRender.opacity === defaultVisibleEnums.show ? '#fff' : undefined,
    };
  },
  img: [
    (styleSettingRender) => {
      // 不是 扁平 不用管
      if (styleSettingRender.goodsStyle !== recommendGoodsStyle.line) {
        return undefined;
      }

      return {
        borderRadius: transform2px(styleSettingRender.borderRadius),
      };
    },
  ],
};

const SplitPrice = ({ price }) => {
  const [priceLeft, priceRight] = splitPrice(price);

  return (
    <View className="sale-price customePageStyle">
      <View className="price-0">¥</View>

      <View className="price-1">{priceLeft}</View>

      <View className="price-2">.{priceRight}</View>
    </View>
  );
};

const ProductTag = ({ product, hasTag }) => {
  if (!hasTag) {
    return null;
  }

  return (
    <View className="tags omit customePageStyle">
      {product?.tagList?.map((str) => {
        return (
          <View className="tag customeSalesPromotionLabelStyle" key={str}>
            <View className="txt">{str}</View>
          </View>
        );
      })}
    </View>
  );
};

const ProductTitle = ({ content, product }) => {
  const hasTag = content?.showTag === defaultVisibleEnums.show && product?.tagList?.length;

  return (
    <>
      <View className={classNames('goods-title', { tag: hasTag })}>{product?.title}</View>

      <ProductTag {...{ product, hasTag }} />
    </>
  );
};

const LeftPanel = ({ content, product }) => {
  const { scribingPrice, price, saleNum } = product;

  const getCartStyle = () => {
    if (content?.showCart !== defaultVisibleEnums.show) {
      return null;
    }

    if (content?.cartStyle === recommendGoodsCartStyle.one) {
      return <Icon name="icon_shopping" className="goods-cart" size={34} />;
    }

    if (content?.cartStyle === recommendGoodsCartStyle.two) {
      return <Icon name="icon_add" className="goods-cart" size={34} />;
    }

    return null;
  };

  return (
    <View className="goods-panel goods-left-panel">
      <ProductTitle {...{ content, product }} />

      <View>
        {content?.showGoodsSaleNum === defaultVisibleEnums.show && (
          <View className="goods-sales">已售{saleNum ?? 0}件</View>
        )}

        <View className="goods-line">
          <View className="goods-price omit">
            <SplitPrice price={price} />

            {content?.showSalePrice === defaultVisibleEnums.show && scribingPrice !== undefined && (
              <View className="del-price">¥{scribingPrice}</View>
            )}
          </View>

          {getCartStyle()}
        </View>
      </View>
    </View>
  );
};

const CenterPanel = ({ content, product }) => {
  const { price } = product;

  return (
    <View className="goods-panel goods-center-panel">
      <ProductTitle {...{ content, product }} />

      <View className="goods-line">
        <SplitPrice price={price} />

        <View
          className={classNames('goods-cart customePageBackgroundStyle', {
            borderRadius: content.cartStyle === recommendGoodsCartStyle.third,
          })}
        >
          <View className="txt">{content?.cartText}</View>
        </View>
      </View>
    </View>
  );
};

const ModuleGoodsTwoColumn = ({
  dispatch,

  styleSettingRender,
  content,
}) => {
  const [appProductList, setAppProductList] = useState([]);
  const [appProductListPagination, setAppProductListPagination] = useState({});

  const style = transformConfig(styleSettingRender, styleConfig);

  const [productInfo, setProductInfo] = useState({ list: [], more: false });

  useEffect(() => {
    if (!content) {
      return;
    }
    appProductListServer({
      appid: Taro.$sassAppId,
      type: 4,
      page: 1,
      pageSize: 10,

      ...content?.goodsSelectInfo,
    }).then((res) => {
      return res?.content ?? {};
    }).then(({ list, pagination }) => {
      setAppProductListPagination(pagination);
      setAppProductList(list);
    });
  }, [content]);

  useEffect(() => {
    // 已经获取过了
    if (productInfo.list?.length) {
      return;
    }

    setProductInfo({
      list: appProductList,
      more: appProductList?.length < appProductListPagination?.totalCount,
    });
  }, [appProductList, appProductListPagination]);

  return (
    <View className="ModuleGoodsTwoColumn" style={{ ...style.module, ...style.background }}>
      {content?.title && (
        <View className="header">
          <View className="theme customePageBackgroundStyle"></View>
          <View className="title">{content?.title}</View>
        </View>
      )}

      <View
        className={classNames('goods-container', {
          [GoodsStyleName[styleSettingRender.goodsStyle]]: true,
        })}
      >
        {productInfo.list?.map((product) => {
          const { id, url, label, isSoldOut } = product;
          const panelProps = { content, product };

          return (
            <View
              className="goods-item"
              key={id}
              style={style.item}
              onClick={() => utils.goGoodDetail(product, dispatch)}
            >
              {label && (
                <View className="goods-label customePageBackgroundStyle">
                  <View className="txt">{label}</View>
                </View>
              )}
              <View className="goods-img-wrap">
                <Image className="goods-img" src={url} style={style.img} />

                {content?.saleOut === defaultVisibleEnums.show && isSoldOut && (
                  <View className="goods-sold-out">
                    <View className="sold-out-container">
                      <View className="txt">售罄</View>
                    </View>
                  </View>
                )}
              </View>
              {content?.goodsAlign === recommendGoodsGoodsAlign.left && (
                <LeftPanel {...panelProps} />
              )}
              {content?.goodsAlign === recommendGoodsGoodsAlign.center && (
                <CenterPanel {...panelProps} />
              )}
            </View>
          );
        })}
      </View>

      {content?.showMore === defaultVisibleEnums.show && productInfo.more && (
        <View className="view-more-wrap">
          <View
            className="view-more"
            onClick={() => {
              Taro.navigateTo({
                url:
                  '/mainSubPack/appProducts/index?goodsSelectInfo=' +
                  JSON.stringify(content?.goodsSelectInfo),
              });
            }}
          >
            <View className="txt">查看更多</View>
          </View>
        </View>
      )}
    </View>
  );
};

export default connect(({ loading }) => ({ loading }))(ModuleGoodsTwoColumn);
